package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.UserLoginBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

public class Dws_UserUserLoginWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_UserUserLoginWindow().init(
                4002,
                2,
                "Dws_UserUserLoginWindow",
                Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        SingleOutputStreamOperator<JSONObject> loginPageStream = findLoginPage(stream);
        SingleOutputStreamOperator<UserLoginBean> beanStream = parseToPojo(loginPageStream);
        SingleOutputStreamOperator<UserLoginBean> resultStream = windowAndAgg(beanStream);
        writeToClickhouse(resultStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<UserLoginBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_user_user_login_window", UserLoginBean.class));
    }

    private SingleOutputStreamOperator<UserLoginBean> windowAndAgg(SingleOutputStreamOperator<UserLoginBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<UserLoginBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs())
                )
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<UserLoginBean>() {
                            @Override
                            public UserLoginBean reduce(UserLoginBean value1, UserLoginBean value2) throws Exception {
                                value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                                value1.setUuCt(value1.getUuCt() + value2.getUuCt());

                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx, Iterable<UserLoginBean> iterable, Collector<UserLoginBean> out) throws Exception {
                                UserLoginBean bean = iterable.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);
                            }
                        }
                );
    }

    private SingleOutputStreamOperator<UserLoginBean> parseToPojo(SingleOutputStreamOperator<JSONObject> loginPageStream) {
        return loginPageStream
                .keyBy(obj -> obj.getJSONObject("common").getString("uid"))
                .process(new KeyedProcessFunction<String, JSONObject, UserLoginBean>() {

                    ValueState<String> lastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {

                        lastVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastVisitDateState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject obj, Context ctx, Collector<UserLoginBean> out) throws Exception {

                        Long ts = obj.getLong("ts");
                        String today = AtguiguUtil.toDate(ts);

                        long backCt = 0L;
                        long uuCt = 0L;
                        String lastVisitDate = lastVisitDateState.value();
                        if (!today.equals(lastVisitDate)) {
                            uuCt = 1L;
                            //更新状态
                            lastVisitDateState.update(today);
                            //TODO 判断是否为 7日回流用户
                            if (lastVisitDate != null) {
                                if ((ts - AtguiguUtil.dateToTs(lastVisitDate)) / 1000 / 60 / 60 / 24 >= 7) {
                                    backCt = 1L;
                                }
                            }
                        }

                        UserLoginBean bean = new UserLoginBean("", "", backCt, uuCt, ts);

                        if (uuCt == 1) {
                            out.collect(bean);
                        }
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> findLoginPage(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .filter(new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject obj) throws Exception {
                        String uid = obj.getJSONObject("common").getString("uid");
//                        boolean lastPageId = obj.getJSONObject("page").containsKey("last_page_id");
//                        if (uid!=null && !lastPageId) {
//                            return true;
//                        }
//                        return false;
                        String lastPageId = obj.getJSONObject("page").getString("last_page_id");

                        return uid != null && lastPageId == null;
                    }
                });
    }
}